<template>
  <el-container class="page-container">
    <!-- 顶部栏 -->
    <el-row class="top-bar">
      <div class="row_Left">
        <div id="l"></div>
        <span>预招生管理</span>
        <el-input 
          v-model="can" 
          placeholder="请输入姓名或手机号" 
          class="search-input"
        />
        <el-input 
          v-model="schoolSearch" 
          placeholder="请输入学校名称" 
          class="search-input"
        />
        <el-button class="search-btn" @click="handleSearch">
          <img src="../../assets/images/搜索.png" alt="搜索" />
          搜索
        </el-button>
      </div>
      <div class="row_Right">
        <img 
          src="../../assets/images/back.png" 
          alt="返回" 
          class="Myimg" 
          id="myimg" 
          @click="goBack"
        />
        <img 
          src="../../assets/images/加号.png" 
          alt="新增" 
          class="Myimg"
          @click="handleAdd"
        />
      </div>
    </el-row>

    <!-- 表格 -->
    <el-row id="buttom">
      <el-table 
        :data="tableData" 
        table-layout="auto"
        :header-cell-style="{ background: '#f5f9fa' }" 
      >
        <el-table-column label="姓名" align="center" prop="studentName" width="80" />
        <el-table-column label="性别" align="center" prop="sex" width="60" />
        <el-table-column width="90" align="center">
          <template #header>
            <el-select 
              class="select_one" 
              v-model="courseFilter" 
              size="small" 
              placeholder="全部"
              @change="fetchData"
            >
              <el-option value="全部">全部</el-option>
              <el-option
                v-for="(item, index) in ClassList" 
                :key="item.courseId" 
                :label="item.courseName"
                :value="item.courseId"
              />
            </el-select>
          </template>
          <template #default="scope">{{ scope.row.preCourse }}</template>
        </el-table-column>
        <el-table-column label="预开班时间" align="center" prop="preDate" width="120" />
        <el-table-column label="电话" align="center" prop="tel" width="140" />
        <el-table-column label="销售顾问" width="100" align="center" prop="saleName">
          <template #header v-if="roleId==1||roleId ==2">
            <el-select 
              class="select_two" 
              v-model="saleFilter" 
              size="small" 
              placeholder="全部"
              @change="fetchData"
            >  
              <el-option value="全部">全部</el-option>
              <el-option
                v-for="(item, index) in saleList" 
                :key="item.userId" 
                :label="item.userName"
                :value="item.userId"
              />
            </el-select>
          </template>
          <template #default="scoped">
            {{ scoped.row.saleName ? scoped.row.saleName : '管理员' }}
          </template>
        </el-table-column>
        <el-table-column label="紧急联系人" align="center" prop="emContact" width="180" />
        <el-table-column label="紧急联系人电话" align="center" prop="emTel" width="200" />
        <el-table-column label="操作" width="160" align="center">
          <template #default="scope">
            <a class="operate-link modify" @click="handleModify(scope.row)">修改</a>
            <a class="operate-link delete" @click="handleDelete(scope.row)">删除</a>
            <a class="operate-link detail" @click="handleDetail(scope.row)">详情</a>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件（优化后） -->
      <div id="fenye">
        <el-pagination
          background
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          layout="prev, pager, next"
          :page-sizes="[5, 10, 15, 20]"
          class="pagination"
          @current-change="handlePaginationChange"
          @size-change="handlePaginationChange"
        />  
        <div id="number"> 
          每页
          <el-input-number
            v-model="pageSize"
            :min="1"
            :max="30"
            controls-position="right"
            @change="handlePaginationChange"
          />条
        </div>
      </div>
    </el-row>

    <!-- 添加预招生模态框 -->
    <div v-if="dialogVisible" class="partial-overlay"></div>
    <el-dialog v-model="dialogVisible" title="添加预招生" width="800px" :show-close="false" :modal="false">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px" hide-required-asterisk>
        <el-row>
          <el-form-item label="姓名" prop="studentName">
            <el-input v-model="formData.studentName" placeholder="请输入学生姓名" />
          </el-form-item>
          <el-form-item label="预报学科" prop="courseId">
            <el-select v-model="formData.courseId" placeholder="请选择预报学科">
              <el-option v-for="(item, index) in ClassList" :key="item.courseId" :label="item.courseName" :value="item.courseId" />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="性别" prop="sex">
            <el-select v-model="formData.sex" placeholder="请选择性别">
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </el-form-item>
          <el-form-item label="预开班日期" prop="preDate">
            <el-date-picker v-model="formData.preDate" type="date" placeholder="请选择预开班日期" style="width: 200px" value-format="YYYY-MM-DD" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="电话" prop="tel">
            <el-input v-model="formData.tel" placeholder="请输入电话" />
          </el-form-item>
          <el-form-item label="预毕业日期" prop="preGraduation">
            <el-date-picker v-model="formData.preGraduation" type="date" placeholder="请选择预毕业日期" style="width: 200px" value-format="YYYY-MM-DD" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="紧急联系人电话" prop="emTel">
            <el-input v-model="formData.emTel" placeholder="请输入紧急联系人电话" />
          </el-form-item>
          <el-form-item label="紧急联系人" prop="emContact">
            <el-input v-model="formData.emContact" placeholder="请输入紧急联系人" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="家庭地址" prop="address">
            <el-input v-model="formData.address" placeholder="请输入家庭地址" />
          </el-form-item>
          <el-form-item label="学校和专业" prop="major">
            <el-input v-model="formData.major" placeholder="请输入学校和专业" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item v-if="roleId==1||roleId==2" label="销售顾问" prop="saleId">
            <el-select v-model="formData.saleId" placeholder="请选择销售顾问" clearable>
              <el-option v-for="(item, index) in saleList" :key="item.userId" :label="item.userName" :value="item.userId" />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="备注" prop="remarks">
            <el-input type="textarea" v-model="formData.remarks" :autosize="{ minRows: 2, maxRows: 4 }" resize="none" style="width: 500px" placeholder="请输入备注" />
          </el-form-item>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false" class="cancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm" class="confirm">确认</el-button>
      </template>
    </el-dialog>

    <!-- 详情抽屉 -->
    <el-drawer v-model="dialogVisible0" title="预招生详情" size="700" :show-close="false" style="background-color:#F0F8FF;">
      <el-row>
        <el-col :span="12">姓名：{{ formData3.studentName }}</el-col>
        <el-col :span="12">性别：{{ formData3.sex }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="12">预开班时间：{{ formData3.preDate }}</el-col>
        <el-col :span="12">预毕业时间：{{ formData3.preGraduation }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="12">电话：{{ formData3.tel }}</el-col>
        <el-col :span="12">学校和专业：{{ formData3.major }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="12">紧急联系人：{{ formData3.emContact }}</el-col>
        <el-col :span="12">紧急联系人电话：{{ formData3.emTel }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="12">预报学科：{{ formData3.preCourse }}</el-col>
        <el-col :span="12">销售顾问：{{ formData3.saleName ? formData3.saleName : '管理员' }}</el-col>
      </el-row>
      <el-row>
        <el-col :span="12">家庭地址：{{ formData3.address }}</el-col>
        <el-col :span="12">报名时间：{{ formData3.transformDate || formData3.createTime.substring(0,10) }}</el-col>
      </el-row>
      <el-row style="display:flex">
        <el-col :span="2">备注：</el-col>
        <el-col :span="22" class="content2">{{ formData3.remarks }}</el-col>
      </el-row>
      <template #footer>
        <el-button @click="dialogVisible0 = false" class="cancel">关闭</el-button>
      </template>
    </el-drawer>
  </el-container>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getPreStudent, addPreStudent, getSaleList, deletePreStudent } from '../api/PreStudent';

// 路由逻辑
const router = useRouter();
const goBack = () => router.push("StudentRecords");

// 用户信息
const userList = JSON.parse(localStorage.getItem("user"));
const userId = ref(userList?.userId || '');
const roleId = ref(userList?.roleId || '');
const UserName = ref(userList?.userName || '');

// 搜索与筛选
const can = ref('');                // 姓名/手机号搜索
const schoolSearch = ref('');       // 学校名称搜索
const courseFilter = ref('全部');   // 课程筛选
const saleFilter = ref('全部');     // 销售筛选

// 表格与分页（优化后）
const tableData = ref([]);          // 表格数据
const currentPage = ref(1);         // 当前页码（统一管理）
const pageSize = ref(5);            // 每页条数（统一管理）
const total = ref(0);               // 总数据量（接口返回）

// 模态框与表单
const dialogVisible = ref(false);   // 添加模态框
const formRef = ref(null);          // 表单引用
const saleList = ref([]);           // 销售顾问列表
const ClassList = ref([]);          // 学科列表
const dialogVisible0 = ref(false);  // 详情抽屉
const formData = reactive({         // 添加表单
  studentName: '', sex: '', courseId: '', preDate: '', preGraduation: '',
  tel: '', address: '', emContact: '', emTel: '', major: '', remarks: '', saleId: ''
});
const formData3 = reactive({});     // 详情数据
const selid = ref(null);            // 区分添加/修改

// 表单验证规则
const rules = ref({
  studentName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  courseId: [{ required: true, message: '请选择预报学科', trigger: 'change' }],
  tel: [{ required: true, message: '请输入电话', trigger: 'blur' }, { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  major: [{ required: true, message: '请输入学校和专业', trigger: 'blur' }],
});

// 初始化数据
onMounted(() => {
  fetchData();
  fetchDataSaleList();
  ClassSaleList();
});

// 核心数据请求（优化分页参数）
const fetchData = () => {
  const isMobile = /^\d+$/.test(can.value);
  const params = {
    pageIndex: currentPage.value,  // 使用统一的当前页码
    pageSize: pageSize.value,      // 使用统一的每页条数
    search: isMobile ? '' : can.value,
    tel: isMobile ? can.value : '',
    major: schoolSearch.value,
  };
  if (saleFilter.value !== "全部") params.userId = saleFilter.value;
  if (roleId.value !== 1 && roleId.value !== 2) params.userId = userId.value;
  if (courseFilter.value !== "全部") params.courseId = courseFilter.value;

  getPreStudent('studentList', params, "post")
    .then(res => {
      if (res.code === 200) {
        // 处理空值显示
        tableData.value = res.dataset.studentList.map(item => ({
          ...item,
          emContact: item.emContact || '--',
          emTel: item.emTel || '--',
          saleName: item.saleName || '管理员'
        }));
        total.value = res.dataset.pageCount*pageSize.value || 0; // 优先使用接口返回的总条数
      }
    })
    .catch(err => console.error("数据请求失败：", err));
};

// 销售顾问列表
const fetchDataSaleList = () => {
  getSaleList('saleName', {}, 'post').then(res => {
    if (res.code === 200) {
      saleList.value = res.dataset;
      saleList.value.unshift({ userId: 0, userName: '管理员' });
    }
  });
};

// 学科列表
const ClassSaleList = () => {
  getSaleList('courseList', {}, 'post').then(res => {
    if (res.code === 200) {
      ClassList.value = [...res.dataset.courseList];
    }
  });
};

// 分页事件处理（合并优化）
const handlePaginationChange = () => {
  // 若为每页条数变化，重置页码为1
  if (arguments.length > 0 && typeof arguments[0] === 'number') {
    currentPage.value = 1;
  }
  fetchData(); // 重新获取数据
};

// 搜索事件
const handleSearch = () => {
  currentPage.value = 1;
  fetchData();
};

// 添加预招生
const handleAdd = () => {
  dialogVisible.value = true;
  formRef.value?.clearValidate();
  formRef.value?.resetFields();
  selid.value = 0;
  Object.assign(formData, {
    studentName: '', sex: '', courseId: '', preDate: '', preGraduation: '',
    tel: '', address: '', emContact: '', emTel: '', major: '', remarks: '', saleId: ''
  });
};

// 提交表单
const handleConfirm = async () => {
  try {
    await formRef.value.validate();
    const selectedCourse = ClassList.value.find(item => item.courseId === formData.courseId);
    const data = {
      studentName: formData.studentName,
      sex: formData.sex,
      courseId: formData.courseId,
      preCourse: selectedCourse ? selectedCourse.courseName : '',
      preDate: formData.preDate,
      preGraduation: formData.preGraduation,
      tel: formData.tel,
      address: formData.address,
      emContact: formData.emContact,
      emTel: formData.emTel,
      major: formData.major,
      remarks: formData.remarks,
      saleId: formData.saleId
    };
    if (roleId.value !== 1 && roleId.value !== 2) data.saleId = userId.value;

    const axio = selid.value === 0 ? "addPreStudent" : "updatePreStudent";
    const cName = selid.value === 0 ? "添加" : "修改";
    if (selid.value === 1) data.studentId = formData.studentId;

    const res = await addPreStudent(axio, data, 'post');
    if (res.code === 200) {
      ElMessage.success(cName + '成功');
      dialogVisible.value = false;
      fetchData();
      formRef.value.resetFields();
    } else {
      ElMessage.error(res.message || cName + '失败');
    }
  } catch (error) {
    ElMessage.error('操作失败');
  }
};

// 修改预招生
const handleModify = (row) => {
  Object.assign(formData, row);
  selid.value = 1;
  dialogVisible.value = true;
};

// 删除预招生
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该预招生信息吗？', '提示', { type: 'warning' })
    .then(() => {
      deletePreStudent('deletePreStudent', { studentId: row.studentId }, 'post').then(res => {
        if (res.code === 200) {
          ElMessage.success('删除成功');
          fetchData();
        }
      });
    })
    .catch(() => ElMessage.info('已取消删除'));
};

// 详情
const handleDetail = (row) => {
  Object.assign(formData3, row);
  dialogVisible0.value = true;
};
</script>

<style lang="less" scoped>
.page-container {
  width: 100%;
  height: 100%;
  background: #f5f9fa;
  display: flex;
  flex-direction: column;
  position: relative;
}

.top-bar {
  width: 90%;
  height: 10%;
  margin: 0 auto;
  background-color: #fff;
  margin-bottom: 20px;
  margin-top: 20px;
  box-shadow: 4px 4px 4px rgba(0, 0, 0, 0.1);
  border-radius: 20px;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.row_Left {
  display: flex;
  align-items: center;
}

#l {
  width: 2px;
  height: 26px;
  background: #007bff;
  margin-left: 20px;
}

span {
  font-size: 20px;
  display: inline-block;
  margin-left: 10px;
}

.search-input {
  box-sizing: border-box;
  width: 170px;
  height: 32px;
  margin-left: 20px;
  border-radius: 12px !important;
}

.search-btn {
  background: #0f6ab1;
  color: #fff;
  margin-left: 10px;
  height: 32px;
  border-radius: 16px;
  cursor: pointer;
  img { margin-right: 5px; }
}

.row_Right {
  display: flex;
  align-items: center;
  padding-right: 40px;
}

.Myimg {
  width: 24px;
  height: 24px;
  cursor: pointer;
  margin-right: 20px;
}

#buttom {
  width: 90%;
  margin: 0 auto;
  background-color: #fff;
  box-shadow: 4px 4px 4px rgba(0, 0, 0, 0.1);
  border-radius: 20px;
  padding: 20px;
}

.el-table {
  width: 100%;
  margin-bottom: 20px;
  &__header th { background: #f5f9fa !important; font-weight: 500; }
  &__body td { border-bottom: 1px solid #eee; }
}

.select_one {
  width: 150px;
  .el-select__wrapper { height: 32px; border-radius: 12px; }
}

.select_two {
  width: 90px;
  .el-select__wrapper { height: 32px; border-radius: 12px; }
}

.operate-link {
  margin-right: 12px;
  cursor: pointer;
  text-decoration: none;
  &.modify { color: #10b981; }  
  &.delete { color: #ef4444; }  
  &.detail { color: #2563eb; }
}

#fenye {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}

#number {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination { text-align: center; }

/* 模态框样式 */
:deep(.el-drawer__header) {
  width: 100%;
  height: 40px;
  background: #0f6abe !important;
  font-size: 20px !important;
  text-align: center;
  line-height: 60px;
  color: #fff;
}
:deep(.el-overlay .el-overlay-dialog) {
  position: fixed !important;
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) !important;
  margin: 0 !important;
  z-index: 3000 !important;
}
:deep(.el-dialog) {
  top: 40px;
  padding: 0px;
  width: 700px;
  margin-top: 100px;
}
:deep(.el-dialog header span) {
  display: inline-block;
  width: 100%;
  background-color: #0f6ab1;
  height: 40px;
  color: white;
  font-size: 15px;
  text-align: center;
  line-height: 40px;
}
:deep(.el-select) { width: 200px; }
:deep(.el-dialog__footer) { text-align: center; padding-bottom: 20px; }
:deep(.confirm) { margin-left: 50px; background-color: #0f6ab1; }
:deep(.cancel) { background-color: #0f6ab1; color: white; }
:deep(.el-dialog__body) { display: flex; justify-content: center; }
:deep(.el-textarea__inner) { min-height: 50px !important; max-height: 100px !important; overflow-y: auto !important; }
.partial-overlay {
  position: fixed;
  top: 80px;
  left: 190px;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
}
</style>